package com.itcam.controller;

import com.itcam.entity.User;
import com.itcam.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping
    @CachePut(cacheNames = "userCache", key = "#user.id") // 最直观的（推荐使用） 如果使用Spring Cache缓存数据，key的生成：userCache::abc
//    @CachePut(cacheNames = "userCache", key = "#result.id") // #result代表当前方法的返回值
//    @CachePut(cacheNames = "userCache", key = "#p0.id") // p0获取到第一个参数
//    @CachePut(cacheNames = "userCache", key = "#a0.id") // a0获取到第一个参数
//    @CachePut(cacheNames = "userCache", key = "#root.args[0].id") // root.args[0]获取到第一个参数
    public User save(@RequestBody User user) {
        userMapper.insert(user);
        return user;
    }

    @GetMapping
    @Cacheable(cacheNames = "userCache", key = "#id") // key的生成：userCache::abc
    public User getById(Long id) {
        User user = userMapper.getById(id);
        return user;
    }

    @DeleteMapping
    @CacheEvict(cacheNames = "userCache", key = "#id") // key的生成：userCache::abc
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }

    @DeleteMapping("/delAll")
    @CacheEvict(cacheNames = "userCache",allEntries = true) // key的生成：userCache::abc
    // entries：键值对
    public void deleteAll() {
        userMapper.deleteAll();
    }

}
